package com.example.othree.controller;

import com.example.othree.entity.TowerOzoneGradientObservations;
import com.example.othree.service.TowerOzoneGradientObservationsService;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/api/tower_ozone")
public class TowerOzoneController {

    private static final Logger logger = LoggerFactory.getLogger(TowerOzoneController.class);
    private String ip = "119.3.48.160";
    private String base_url = "http://"+ip+"/agms-prj-server/api/v1/web/outside/";

    @Autowired
    private TowerOzoneGradientObservationsService towerService;

    // 定时采集铁塔数据(凌晨一点执行)
    @Scheduled(cron = "0 0 1 * * ?")
    public void dataCollection() {

        LocalDateTime now;
        LocalDateTime previousDay = null;
        LocalDateTime twentyFourHoursAgo = null;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");

        // 获取当前时间
        now = LocalDateTime.now();

        // 获取前一天的当前时间
        previousDay = now.minusHours(1);


        // 获取24小时前的时间
        twentyFourHoursAgo = now.minus(24, ChronoUnit.HOURS);
        // 将时间格式化为字符串
        String previousDayStr = previousDay.format(formatter);
        String twentyFourHoursAgoStr = twentyFourHoursAgo.format(formatter);


        // 调接口
        try {

            // Set up the parameters
            String userName = "hbhsxt"; // Fill in the actual username
            String password = "18a9fc68beab907b24dc3bb56971052c"; // Fill in the actual password
            String stationCode = "CEG22460001*"; // Fill in the station code
            String start = previousDayStr; // Start time in yyyyMMddHHmm format
            String end =   twentyFourHoursAgoStr;   // End time in yyyyMMddHHmm format

            // Construct the URL
            String urlString = String.format(
                    ""+base_url+"site-data-time?UserName=%s&Password=%s&StationCode=%s&StartTime=%s&EndTime=%s",
                    userName, password, stationCode, start, end);

            // Create a URL object
            URL url = new URL(urlString);
            // Open a connection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // Set the request method to GET
            connection.setRequestMethod("GET");
            // Set the content type
            connection.setRequestProperty("Content-Type", "multipart/form-data");

            // Get the response code
            int responseCode = connection.getResponseCode();

            // If response code is 200 (OK), read the response
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                // Read the response line by line
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();


                ObjectMapper mapper = new ObjectMapper();

                try {
                    // Parse JSON to Root object
                    Root root = mapper.readValue(response.toString(), Root.class);

                    // Access data

                    String longitude = root.content.longitude;
                    String latitude =  root.content.latitude;
                    String StationCode = root.content.stationCode;
                    String pointName = root.content.pointName;

                    for (Data_ data : root.content.data) {
                        double co = data.co;
                        double no2 = data.no2;
                        double o3 = data.o3;
                        double so2 = data.so2;
                        String time = data.time;

                        TowerOzoneGradientObservations tower = new TowerOzoneGradientObservations();

                        tower.setLongitude(Double.parseDouble(longitude));
                        tower.setLatitude(Double.parseDouble(latitude));
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
                        tower.setTime(sdf.parse(time));
                        tower.setStationCode(StationCode);
                        tower.setPointName(pointName);
                        tower.setCo(co);
                        tower.setNo2(no2);
                        tower.setO3(o3);
                        tower.setSo2(so2);

                        towerService.save(tower);

                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }

                logger.info("采集"+start, "-" + now+"数据完成");



            } else {
                logger.error("GET request failed.");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 手动采集数据方法，弃用
    @ApiOperation("手动采集铁塔数据")
    @GetMapping("/collection")
    public void dataCollection(@RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
                               @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
                               @RequestParam(value = "stationCode", required = false) String stationCode) {


        LocalDateTime now;
        LocalDateTime previousDay = null;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");


        now = startTime;
        previousDay = endTime;


        // 将时间格式化为字符串
        String previousDayStr = previousDay.format(formatter);
        String twentyFourHoursAgoStr = now.format(formatter);


        // 调接口
        try {

            // Set up the parameters
            String userName = "hbhsxt"; // Fill in the actual username
            String password = "18a9fc68beab907b24dc3bb56971052c"; // Fill in the actual password
//            String stationCode = "CEG22460001*"; // Fill in the station code
            String start = twentyFourHoursAgoStr; // Start time in yyyyMMddHHmm format
            String end =   previousDayStr;   // End time in yyyyMMddHHmm format

            // Construct the URL
            String urlString = String.format(
                    ""+base_url+"site-data-time?UserName=%s&Password=%s&StationCode=%s&StartTime=%s&EndTime=%s",
                    userName, password, stationCode, start, end);

            // Create a URL object
            URL url = new URL(urlString);
            // Open a connection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // Set the request method to GET
            connection.setRequestMethod("GET");
            // Set the content type
            connection.setRequestProperty("Content-Type", "multipart/form-data");

            // Get the response code
            int responseCode = connection.getResponseCode();

            // If response code is 200 (OK), read the response
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                // Read the response line by line
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();


                ObjectMapper mapper = new ObjectMapper();

                try {
                    // Parse JSON to Root object
                    Root root = mapper.readValue(response.toString(), Root.class);

                    // Access data

                    String longitude = root.content.longitude;
                    String latitude =  root.content.latitude;
                    String StationCode = root.content.stationCode;
                    String pointName = root.content.pointName;

                    for (Data_ data : root.content.data) {
                        double co = data.co;
                        double no2 = data.no2;
                        double o3 = data.o3;
                        double so2 = data.so2;
                        String time = data.time;

                        TowerOzoneGradientObservations tower = new TowerOzoneGradientObservations();

                        tower.setLongitude(Double.parseDouble(longitude));
                        tower.setLatitude(Double.parseDouble(latitude));
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
                        tower.setTime(sdf.parse(time));
                        tower.setStationCode(StationCode);
                        tower.setPointName(pointName);
                        tower.setCo(co);
                        tower.setNo2(no2);
                        tower.setO3(o3);
                        tower.setSo2(so2);

                        towerService.save(tower);

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }



            } else {
                System.out.println("GET request failed.");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // TODO 河北臭氧综合监测信息处理平台接口需求-3-铁塔页面接口需求-2024.9.24.docx 文档中的接口
}


@Data
class Data_ {
    @JsonProperty("O3")
    public double o3;

    @JsonProperty("Time")
    public String time;

    @JsonProperty("CO")
    public double co;

    @JsonProperty("WD")
    public double wd;

    @JsonProperty("NO2")
    public double no2;

    @JsonProperty("TVOC")
    public double tvoc;

    @JsonProperty("PRESSURE")
    public double pressure;

    @JsonProperty("TEMP")
    public double temp;

    @JsonProperty("RH")
    public double rh;

    @JsonProperty("SO2")
    public double so2;

    @JsonProperty("PM2.5")
    public double pm25;

    @JsonProperty("PM10")
    public double pm10;

    @JsonProperty("AQI")
    public int aqi;

    @JsonProperty("WS")
    public double ws;

    @JsonProperty("status")
    public String status;
}

@Data
class Content {
    @JsonProperty("Area")
    public String area;

    @JsonProperty("Latitude")
    public String latitude;

    @JsonProperty("Data")
    public List<Data_> data;

    @JsonProperty("StationCode")
    public String stationCode;

    @JsonProperty("PointName")
    public String pointName;

    @JsonProperty("Longitude")
    public String longitude;
}

@Data
class Root {
    @JsonProperty("Content")
    public Content content;

    @JsonProperty("Code")
    public String code;
}
